/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.teacake.filteringproxy;
import java.net.*;
import java.io.*;
/**
 *
 * @author tkleisas
 */
public class HttpClient
{
    public HttpClient()
    {
        m_socket = new java.net.Socket();
    }
   
    public void connect(String host, int port)
    {
        try
        {
            java.net.InetSocketAddress address = new java.net.InetSocketAddress(host, port);            
            m_socket.connect(address);
            m_in = m_socket.getInputStream();
            m_out = m_socket.getOutputStream();
        }
        catch(java.io.IOException eio)
        {
            System.out.println(eio.getMessage());

        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    public byte[] doRequest(byte[] request, long timeout)
    {
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try
        {
            m_out.write(request);
            int readLen = 0;
            int c=0;
            while((c = m_in.read())!=-1)
            {
                baos.write(c);
            }
                
                
                
                
           
            

        }
        catch(java.io.IOException eio)
        {
            System.out.println(eio.getMessage());
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            try
            {
                m_in.close();
            }
            catch(Exception e1)
            {

            }
            try
            {
                m_out.close();
            }
            catch(Exception e2)
            {

            }
            try
            {
                m_socket.close();
            }
            catch(Exception e3)
            {

            }

        }
        m_response = baos.toByteArray();
        return m_response;
    }
    private Socket m_socket;
    private byte[] m_request;
    private byte[] m_response;
    private byte[] m_headers;
    private java.io.InputStream m_in;
    private java.io.OutputStream m_out;
    public static void main (String[] args)
    {
        HttpClient client = new HttpClient();
        client.connect("www.in.gr",80 );
        byte[] data = client.doRequest("GET http://www.in.gr/ HTTP/1.1\r\n\r\n".getBytes(), 15000);
        System.out.println("SERVER RESPONSE\r\n---------------\r\n"+new String(data));
        HttpHeader header = null;
        try
        {
            header = new HttpHeader(data);
            System.out.println(header.printHeaders());
        }
        catch(RuntimeException rex)
        {
            System.out.println("incomplete message");
        }
        
        
        
    }
}
